package models

import (
	"errmsg"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"time"
	"tools"
)

type Messages struct {
	Id         string `orm:"column(id);pk" json:"id" form:"id"`
	UserId     string `orm:"column(user_id)" json:"user_id" form:"user_id"`
	FromUserId string `orm:"column(from_user_id)" json:"from_user_id" form:"from_user_id"`
	Type       string `orm:"column(type)" json:"type" form:"type"`
	Sta        string `orm:"column(sta)" json:"sta" form:"sta"`
	Title      string `orm:"column(title)" json:"title" form:"title"`
	Content    string `orm:"column(content)" json:"content" form:"content"`
	Voice      string `orm:"column(voice)" json:"voice" form:"voice"`
	CreateTime int64  `orm:"column(create_time)" json:"create_time" form:"create_time"`
	FromUser   *User  `orm:"-" json:"from" form:"-"`
}

func (m *Messages) TableName() string {
	return "messages"
}

func init() {
	orm.RegisterModel(new(Messages))
}

func NewMessages() *Messages {
	return &Messages{}
}

func GetAllMessageByUid(uid string, page int) ([]*Messages, error) {
	var (
		lists []*Messages
		qs    orm.QuerySeter
		err   error
	)

	qs = orm.NewOrm().QueryTable(NewMessages().TableName()).Filter("user_id", uid).OrderBy("-create_time")
	if page > 0 {
		row := beego.AppConfig.DefaultInt("page_limit", 20)
		start := (page - 1) * row
		qs = qs.Limit(row).Offset(start)
	}

	if _, err = qs.All(&lists); err != nil {
		logs.Error(err)
		return nil, err
	}

	if len(lists) == 0 {
		return nil, nil
	}

	for k, v := range lists {
		if len(v.FromUserId) > 0 {
			lists[k].FromUser, _ = GetUserById(v.FromUserId)
		}
	}

	return lists, nil
}

// 添加日志
func AddMessage(uid, title, content string, params ...interface{}) error {
	sql := `INSERT INTO messages (id, user_id, title, content, create_time, type) VALUES (?, ?, ?, ?, ?, ?)`
	_, err := orm.NewOrm().Raw(sql, tools.GUUID(), uid, title, content, time.Now().Unix(), "log").Exec()
	if err != nil {
		logs.Warn("add messages error:", err)
		return err
	}
	return nil
}

// 清空日志
func ClearMessagesByUid(uid string) bool {
	sql := `DELETE FROM messages WHERE user_id = ?`
	res, err := orm.NewOrm().Raw(sql).SetArgs(uid).Exec()
	if err != nil {
		logs.Error("clear messages error:", err)
		return false
	}
	c, err := res.RowsAffected()
	if err != nil {
		logs.Error("clear messages error:", err)
		return false
	}
	if c == 0 {
		return false
	}
	return true
}

func PushMessage(uid, alter string, jumpUrl string, extras ...map[string]interface{}) error {
	// 推送消息
	jclient := tools.NewJpush().SetAlias(uid).SetAlert(alter)
	if len(jumpUrl) > 0 {
		jclient = jclient.Jump(jumpUrl)
	}

	if len(extras) > 0 {
		for key, v := range extras[0] {
			jclient = jclient.AddExtras(key, v)
		}
	}

	if err := jclient.Send(); err != nil {
		logs.Error(err)
		return errmsg.ErrResponseSystem
	}

	// 记录日志
	if err := AddMessage(uid, "", alter); err != nil {
		logs.Error(err)
		return err
	}

	return nil
}
